/**
 * @file ext-polystar.js
 *
 *
 * @copyright 2010 CloudCanvas, Inc. All rights reserved
 * @copyright 2021 Optimistik SAS, Inc. All rights reserved
 * @license MIT
 *
 */
// 网格工具
const name = 'table'

const loadExtensionTranslation = async function (svgEditor) {
  let translationModule
  const lang = svgEditor.configObj.pref('lang')
  try {
    translationModule = await import(`./locale/${lang}.js`)
  } catch (_error) {
    console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
    translationModule = await import('./locale/en.js')
  }
  svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
}

export default {
  name,
  async init() {
    const svgEditor = this
    const { svgCanvas } = svgEditor
    const { ChangeElementCommand } = svgCanvas.history
    const addToHistory = (cmd) => { svgCanvas.undoMgr.addCommandToHistory(cmd) }
    const { $id, $click, $qq } = svgCanvas
    let selElems
    let started
    let newFO
    let p = {
      x1:0,
      x2:0,
      y1:0,
      y2:0,
      ws:100,
      hs:60,
      col:0,
      row:0,
      last_col:0,
      last_row:0
    }
    await loadExtensionTranslation(svgEditor)

    /**
     *
     * @param {string} attr attribute to change
     * @param {string|Float} val new value
     * @returns {void}
     */
    const setAttr = (attr, val) => {
      svgCanvas.changeSelectedAttribute(attr, val)
      svgCanvas.call('changed', selElems)
    }

    /**
     * @param {Float} n angle
     * @return {Float} cotangeante
     */
    const creatVerticalLine = (p) => {
      var n = p.col +1
      for(var i=0;i<n;i++){
        createSvgLine({x1:p.x1 + i*p.ws,y1:p.y1,x2:p.x1 + i*p.ws,y2:p.y1+p.row*p.hs})
      }
    }
    const createHorizoneLine = (p) => {
      var n = p.row +1
      for(var i=0;i<n;i++){
        createSvgLine({x1:p.x1,y1:p.y1 + i*p.hs,x2:p.x1 + p.col*p.ws,y2:p.y1 + i*p.hs})
      }
    }
    const createSvgLine = (p)=>{
      var rect = svgCanvas.addSVGElementsFromJson({
        element: 'line',
        curStyles: false,
        attr: {
          x1:p.x1,
          y1:p.y1,
          x2:p.x2,
          y2:p.y2,
          class:"tableLine",
          id: svgCanvas.getNextId(),
          'stroke':'#cccccc',
          'stroke-width': 2,
          'stroke-dasharray':"5,5",
           'stroke-linecap':"round"
        }
      })
      newFO.append(rect)
    }

    const createTable=(p)=>{
      var col = Math.floor(Math.abs(p.x2-p.x1)/p.ws)
      var row = Math.floor(Math.abs(p.y2-p.y1)/p.hs)
      if(col == 0 || row ==0){
        return
      }
      p.col = col
      p.row = row
      if(p.col == p.last_col && p.row==p.last_row){
        return
      }
      $(newFO).empty()
      creatVerticalLine(p)
      createHorizoneLine(p)
      p.last_col = col
      p.last_row = row
    }

    return {
      name: svgEditor.i18next.t(`${name}:name`),
      // The callback should be used to load the DOM with the appropriate UI items
      callback() {
        // Add the button and its handler(s)
        // Note: the star extension needs to be loaded before the polygon extension
        const fbtitle = `${name}:title`
        const titleStar = `${name}:buttons.0.title`
        const titlePolygon = `${name}:buttons.1.title`
        const buttonTemplate = `
              <se-button id="tool_table" title="${titlePolygon}" src="table.svg">
              </se-button>
          `
        svgCanvas.insertChildAtIndex($qq('.shaps .itemWrap'), buttonTemplate, 8)

        $click($id('tool_table'), () => {
          if (this.leftPanel.updateLeftPanel('tool_table')) {
            svgCanvas.setMode('table')
          }
        })
      },
      mouseDown(opts) {
        // TODO:
        var eles = svgCanvas.getSelectedElements()
        if (svgCanvas.getMode() === 'resize' && (eles.length == 1 && eles[0].classList.contains("table"))) {
            p.x1 = eles[0].getBBox().x
            p.y1 = eles[0].getBBox().y
            p.x2 = eles[0].getBBox().x + eles[0].getBBox().width +5
            p.y2 = eles[0].getBBox().y + eles[0].getBBox().height+5
            var lines = $(eles[0]).find(".tableLine")
            var length = lines.length;
            p.ws = $(lines[1]).attr("x2") - $(lines[0]).attr("x2");
            p.hs = $(lines[length-1]).attr("y2") - $(lines[length-2]).attr("y2")
            newFO = eles[0]
            started = true
        }
        if (svgCanvas.getMode() === 'table') {
          started = true
          p.x1 = opts.start_x
          p.y1 = opts.start_y
          newFO = svgCanvas.addSVGElementsFromJson({
            element: 'g',
            attr: {
              class:'table ems',
              'doc-type':'table',
              id: svgCanvas.getNextId()
            }
          })

          return {
            started: true
          }
        }
        return undefined
      },
      mouseMove(opts) {
        if (!started) {
          return undefined
        }
        const zoom = svgCanvas.getZoom()
         let x = opts.mouse_x / zoom
         let y = opts.mouse_y / zoom
         var eles = svgCanvas.getSelectedElements()
         var doResize = false
        var doResize = false
         if (svgCanvas.getMode() === 'resize') {
           if (eles.length == 1 && eles[0].classList.contains("table")) {
             doResize = true
             p.x1 = eles[0].getBBox().x
             p.y1 = eles[0].getBBox().y
             if (svgCanvas.getCurrentResizeMode().includes('se')) {
               p.x2 = x+2
               p.y2 = y+2
             } else if (svgCanvas.getCurrentResizeMode().includes('e')) {
               p.x2 = x+2
             } else if (svgCanvas.getCurrentResizeMode().includes('s')) {
               p.y2 = y+2
             }else{
               return
             }
           } else {
             return
           }
         }
        if (svgCanvas.getMode() === 'table') {
          p.x2 = x
          p.y2 = y
        }
        if (svgCanvas.getMode() === 'table' || (svgCanvas.getMode() === 'resize' && doResize)) {
          createTable(p)
          if (svgCanvas.getMode() === 'resize') {
            svgCanvas.selectorManager.requestSelector(eles[0]).resize()
            svgCanvas.call('transition', eles[0])
          }
          return {
            started: true
          }
        }
        return undefined
      },
      mouseUp() {
        if (svgCanvas.getMode() === 'table') {
          const keep = p.col>=1&&p.row>=1
          return {
            keep,
            element: newFO
          }
        }
        return undefined
      },
    }
  }
}
